import axios from 'axios'
import type { AxiosInstance } from 'axios'
import { ElMessage } from 'element-plus'

const serverConfig = {
    baseURL: "",
    useTokenAuth: true,
}

const httpRequest = axios.create({
    baseURL: serverConfig.baseURL,
    timeout: 150_000,
    withCredentials: false,
}) as AxiosInstance

httpRequest.interceptors.request.use(config => {
    if (serverConfig.useTokenAuth) {
        const token = localStorage.getItem('token')
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`;
        }
    }
    return config
}, error => {
    return Promise.reject(error)
})

httpRequest.interceptors.response.use(
    (response) => {
        return response.data
    },
    (error) => {
        console.log("error",error)
        if (error.response) {
            const { status } = error.response
            
            switch (status) {
                case 401:
                    // Token 过期或无效，清除本地存储并跳转到登录页
                    localStorage.removeItem('token')
                    localStorage.removeItem('user')
                    ElMessage.error('登录已过期，请重新登录')
                    window.location.href = '/login'
                    break
                case 403:
                    ElMessage.error('没有权限访问该资源')
                    break
                case 404:
                    ElMessage.error('请求的资源不存在')
                    break
                case 500:
                    ElMessage.error('服务器内部错误')
                    break
                default:
                    ElMessage.error(error.response.data?.message || '请求失败')
            }
        } else {
            ElMessage.error('网络错误，请检查网络连接')
        }
        
        return Promise.reject(error)
    }
)

export {
    httpRequest
}